#!/usr/bin/env python3.9
# -*- encoding: utf-8 -*-
"""
@文件        :result.py
@说明        :响应信息统一结果
@时间        :2022/11/28 20:27:26
@作者        :Mars
@版本        :1.0
"""

from .enums import StatusCodeEnum


class R(object):
    """
    统一项目信息返回结果类
    """

    def __init__(self):
        self.success = None
        self.code = None
        self.msg = None
        self._data = dict()

    @staticmethod
    def ok():
        """
        组织成功响应信息
        :return:
        """
        r = R()
        r.success = True
        r.code = StatusCodeEnum.OK.code
        r.msg = StatusCodeEnum.OK.errmsg
        return r

    @staticmethod
    def error():
        """
        组织错误响应信息
        :return:
        """
        r = R()
        r.success = False
        r.code = StatusCodeEnum.ERROR.code
        r.msg = StatusCodeEnum.ERROR.errmsg
        return r

    @staticmethod
    def server_error():
        """
        组织服务器错误信息
        :return:
        """
        r = R()
        r.success = False
        r.code = StatusCodeEnum.SERVER_ERR.code
        r.msg = StatusCodeEnum.SERVER_ERR.errmsg
        return r

    @staticmethod
    def set_result(enum):
        """
        组织对应枚举类的响应信息
        :param enum: 状态枚举类
        :return:
        """
        r = R()
        r.success = enum.code==0 
        r.code = enum.code
        r.msg = enum.errmsg
        return r

    def data(self, obj=None):
        """统一后端返回的数据"""
        self._data = obj
        context = {"success":self.success,"code": self.code, "msg": self.msg,}
        if self._data:
            context['data'] =  self._data
        return context

    def error(self, detail=None):

        context = {
            "success":self.success,
            "code": self.code,
            "msg": self.msg,
        }
        if detail:
            context["err_detail"] = detail
        return context
